import { DownOutlined } from '@/components/Icon';
import { sysProfileControllerProfile as queryCurrentUser } from '@/services/ess/sysProfile';
import { useIntl, useModel } from '@umijs/max';
import type { CascaderProps, GetProp } from 'antd';
import { Cascader, message, Popover } from 'antd';
import { flushSync } from 'react-dom';

type DefaultOptionType = GetProp<CascaderProps, 'options'>[number];

interface Option {
  value?: string;
  label?: string;
  oldStation?: boolean;
  isArea?: boolean;
  uiVersion?: number;
  children?: Option[];
  disabled?: boolean;
}

const Index: React.FC<{ title: string }> = () => {
  const intl = useIntl();
  const { initialState, setInitialState } = useModel('@@initialState');
  const { tenants, stationName, stationId, tenantId } = initialState || {};
  const options: Option[] = (tenants || [])
    .map((item) => {
      const tenantObj: Option = {};
      tenantObj.label = item.tenantName;
      tenantObj.value = item.tenantId?.toString();
      tenantObj.children = (item.stationInfos ?? []).map((station) => {
        const stationObj: Option = {};
        stationObj.label = station.stationName;
        stationObj.oldStation = station.oldStation;
        stationObj.uiVersion = station.uiVersion;
        stationObj.value = station.id?.toString();
        return stationObj;
      });
      return tenantObj;
    })
    .filter((item) => item.children?.length);

  const onChange = async (value: string[], selectedOptions: Option[]) => {
    console.log('selection', selectedOptions);
    if (!value) {
      return;
    }

    flushSync(() => {
      setInitialState((s) => ({
        ...s,
        tenantId: value[0],
        stationId: value[1],
        stationName: selectedOptions[1]?.label,
        stationCode: selectedOptions[1].stationCode,
        oldStation: selectedOptions[1]?.oldStation,
        isArea: selectedOptions[1]?.isArea,
        uiVersion: selectedOptions[1]?.uiVersion,
      }));
      sessionStorage.setItem('stationId', value[1] || '');
      message.success(intl.formatMessage({ id: 'login.switchStaion' }));
    });

    // 调用 queryCurrentUser 函数并更新 initialState
    try {
      const currentUser = await queryCurrentUser();
      setInitialState((s) => ({
        ...s,
        currentUser,
      }));
      // 手动刷新页面以重新加载数据
      window.location.reload();
    } catch (error) {
      message.error(intl.formatMessage({ id: 'login.usrInfo' }));
    }
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <div
      onClick={(event) => {
        event.stopPropagation();
        event.nativeEvent.stopImmediatePropagation();
      }}
      style={{ display: 'flex', fontSize: 20, fontWeight: 600, marginLeft: 12 }}
    >
      <span>{intl.formatMessage({ id: 'login.poster' })}&nbsp;&nbsp;</span>
      {stationName ? (
        <>
          <span style={{ fontSize: 14 }}>|</span>
          <Popover
            content={
              <Cascader
                options={options}
                onChange={onChange}
                placeholder="Please select"
                showSearch={{ filter }}
                onSearch={(value) => console.log(value)}
                value={[tenantId, stationId]}
                allowClear={false}
                style={{ width: 280 }}
              />
            }
            title={false}
            arrow={false}
            trigger="click"
            placement="bottomLeft"
          >
            <div
              onClick={(e) => e.preventDefault()}
              style={{
                cursor: 'pointer',
                display: 'flex',
                alignContent: 'center',
                paddingLeft: 12,
              }}
            >
              {stationName}
              <DownOutlined
                style={{
                  maxHeight: 60,
                  paddingLeft: 10,
                  paddingTop: 2,
                  marginLeft: 3,
                }}
              />
            </div>
          </Popover>
        </>
      ) : null}
    </div>
  );
};

export default Index;
